package com.other;

import java.util.Random;

/**
 * 三门问题
 */
public class ThreeDoorSolution {
    public static void main(String[] args) {
        // 模拟执行1万次，打印获胜的概率
        threeDoor(10000);
    }

    /**
     * 三门问题逻辑拆解
     *
     * @param numSimulations 总共执行多少轮游戏
     */
    private static void threeDoor(int numSimulations) {
        int switchWins = 0;
        int stayWins = 0;

        Random random = new Random();
        for (int i = 0; i < numSimulations; i++) {
            // 随机确定车所在的门
            int carDoor = random.nextInt(3);

            // 玩家随机选择一扇门
            int playerChoice = random.nextInt(3);

            // 主持人随机打开一扇门：要求该门不是玩家选择的，且必须是羊
            int openedDoor;
            do {
                openedDoor = random.nextInt(3);
            } while (openedDoor == carDoor || openedDoor == playerChoice);

            // 换门后的选择：不能是打开的门，不能是玩家选择的门，则是交换之后的门
            int finalChoice;
            do {
                finalChoice = random.nextInt(3);
            } while (finalChoice == playerChoice || finalChoice == openedDoor);

            // 计算是否换门获胜
            if (finalChoice == carDoor) {
                switchWins++;
            }

            // 计算不换门获胜
            if (playerChoice == carDoor) {
                stayWins++;
            }
        }

        // 输出结果
        System.out.println("在 " + numSimulations + " 次模拟中：");
        System.out.println("换门获胜的概率：" + (double) switchWins / numSimulations);
        System.out.println("不换门获胜的概率：" + (double) stayWins / numSimulations);
    }
}